/**
 * 
 */
package hu.gbalage.owlforms.xforms;

import hu.gbalage.owlforms.api.Form;
import hu.gbalage.owlforms.api.data.FormData;
import hu.gbalage.owlforms.xforms.work.Boot;
import hu.gbalage.owlforms.xforms.work.FormsCache;
import hu.gbalage.owlforms.xforms.work.IOWLForms;
import hu.gbalage.owlforms.xforms.work.XFormsCache;

import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @author balage
 *
 */
public class DontesHandler implements HttpHandler {

	private void insertData(Element root, Element data, URI uri){
		//System.out.println(root.getNodeName()+": "+root.getAttribute("input")+", "+root.getAttribute("class"));
		if (root.getNodeName().equals("value") && root.getAttribute("input").equals("uri")){
			//System.out.println("----------Inserting URI");
			root.setTextContent(uri.toString());
		}else
		if (root.getNodeName().equals("xhtml:div") && root.getAttribute("class").equals("import")){
			//System.out.println("----------Inserting DATA");
			root.appendChild(data);
		}else{
			NodeList list = root.getChildNodes();
			for(int i = 0;i<list.getLength();i++){
				if (list.item(i) instanceof Element){
					insertData((Element)list.item(i), data, uri);
				}
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange)
	 */
	@Override
	public void handle(HttpExchange arg0) throws IOException {
		try{
		arg0.sendResponseHeaders(200, 0);
		
		String uri = arg0.getRequestURI().getQuery();
		
		if (uri.startsWith("uri=")) uri = uri.substring(4);
		
		Document doc = XFormsCache.generateXForms(IOWLForms.Form_Dontes, null);
		
		Form form = FormsCache.getForm(IOWLForms.Form_Szoctam);
		
		FormData loaded = Boot.load(form, uri);
		
		FormDataPrinter printer = new FormDataPrinter();
		
		Element input = printer.toXHTML(doc, loaded);
		
		insertData(doc.getDocumentElement(), input, URI.create(Constants.OWLForms_SAVE_BASE+uri));
		
		XMLHelper.serialize(doc,arg0.getResponseBody());
		
		}catch (Exception e) {
			e.printStackTrace();
			arg0.sendResponseHeaders(500, 0);
			PrintStream p = new PrintStream(arg0.getResponseBody());
			e.printStackTrace(p);
		}
		arg0.close();
	}

}
